import { useCallback } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import type { RootState, AppDispatch } from '../store';
import {
  fetchMembers,
  createMember,
  updateMember,
  deleteMember,
  clearError
} from '../store/slices/memberSlice';
import type {
  CreateMemberRequest as SliceCreateMemberRequest,
  UpdateMemberRequest as SliceUpdateMemberRequest
} from '../store/slices/memberSlice';

export const useMember = () => {
  const dispatch = useDispatch<AppDispatch>();
  const { members, loading, error } = useSelector((state: RootState) => state.member);

  const initMembers = useCallback(() => {
    dispatch(fetchMembers());
  }, [dispatch]);

  const refreshMembers = useCallback(() => {
    dispatch(fetchMembers());
  }, [dispatch]);

  const addMember = useCallback(async (memberData: SliceCreateMemberRequest) => {
    try {
      const result = await dispatch(createMember(memberData)).unwrap();
      return result;
    } catch (error) {
      console.error('添加人员失败:', error);
      throw error;
    }
  }, [dispatch]);

  const modifyMember = useCallback(async (memberData: SliceUpdateMemberRequest) => {
    try {
      const result = await dispatch(updateMember(memberData)).unwrap();
      return result;
    } catch (error) {
      console.error('更新人员失败:', error);
      throw error;
    }
  }, [dispatch]);

  const removeMember = useCallback(async (memberId: number) => {
    try {
      await dispatch(deleteMember(memberId)).unwrap();
      return true;
    } catch (error) {
      console.error('删除人员失败:', error);
      throw error;
    }
  }, [dispatch]);

  const clearMemberError = useCallback(() => {
    dispatch(clearError());
  }, [dispatch]);

  return {
    // 状态
    members,
    loading,
    error,

    // 操作方法
    initMembers,
    refreshMembers,
    createMember: addMember,
    modifyMember,
    removeMember,
    clearError: clearMemberError,
  };
};